package sandau.self_improvement_wall.security;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author LuanZheng
 * @date 2025/5/14 12:03
 */
@Component
public class IpRateLimitInterceptor implements HandlerInterceptor {
    private final RateLimiter rateLimiter;

    public IpRateLimitInterceptor(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String ip = getClientIp(request);
//        if (!rateLimiter.allowRequest(ip)) {
//            response.setContentType("application/json");
//            response.setStatus(429);
//            response.getWriter().write("{\"error\": \"Too many requests\"}");
//            return false;
//        }
        return true;
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.split(",")[0].trim(); // 处理多级代理情况
    }
}
